import redi_messages as please

try:
    import MySQLdb
except ImportError: 
    please.say("Things that make you go hmmm...", 
               "The MySQLdb module is pretty much needed to load the 'database'",
               "Without it there may be a cryptic error message below", 
               "Don't panic, just copy/paste this link into your 'browser'", "\thttp://mysql-python.sourceforge.net")

def create(dataset_id, config):
    conn = connect(config)
    conn.cursor().execute("CREATE DATABASE " + dataset_id)
    conn.cursor().execute("GRANT SELECT ON " + dataset_id + ".* TO 'REDI'@'%'")
    conn.cursor().execute("GRANT SELECT ON " + dataset_id + ".* TO 'REDI'@'localhost'")

def drop(dataset_id, config):
    conn = connect(config)
    conn.cursor().execute("DROP DATABASE " + dataset_id)

def connect(config):
    host = "localhost"
    port = 3306
    user = "root"
    passwd= ""

    if config.has_option("MySQL", "host"): host = config.get("MySQL", "host")
    if config.has_option("MySQL", "port"): port = config.getint("MySQL", "port")
    if config.has_option("MySQL", "user"): user = config.get("MySQL", "user")
    if config.has_option("MySQL", "passwd"): passwd = config.get("MySQL", "passwd")

    return MySQLdb.connect(host=host, port=port, user=user, passwd=passwd)

def execute(dataset_id, sqlcmds, config, options):
    conn = connect(config)
    conn.cursor().execute("USE " + dataset_id)
    for sqlcmd in sqlcmds:
        if options.verbose: print "===> EXECUTING: " + sqlcmd
        conn.cursor().execute(sqlcmd)

def execute_from_template(dataset_id, sql_template, config, options):
    rfile = open(sql_template)
    sqlstmt = " ".join([line for line in rfile.readlines()])
    if options.verbose: print "===> EXECUTING:\n" + sqlstmt

    conn = connect(config)
    conn.cursor().execute("USE " + dataset_id)
    conn.cursor().execute(sqlstmt)

def bulk_load(dataset_id, imported_item, config, options):
    print "sqldb.bulk_load(%s)"%(dataset_id)

    table = imported_item["table"]
    schema = imported_item["schema"]
    type = imported_item["type"]

    columnSql = []
    for column in schema:
        colname = column["name"]
        coltype = column["type"]
        # TODO : Add more supported data types
        if coltype == "string":  columnSql.append(colname + " TEXT")
        elif coltype == "int":  columnSql.append(colname + " INT")
        elif coltype == "double":  columnSql.append(colname + " DOUBLE")
        else: columnSql.append(colname + " TEXT")

    createTable = "CREATE TABLE %s (%s)" %(table, ", ".join(columnSql))
    loadfile = "/".join([dataset_id, type, table])

    loadDataInFile = "LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'" % (loadfile,table)
    execute(dataset_id, [createTable, loadDataInFile], config, options)
